package com.smartrobot.smartrobot.websocket;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.smartrobot.smartrobot.Common.CommonFunc;
import com.smartrobot.smartrobot.activity.MainActivity;
import com.smartrobot.smartrobot.activity.SplashActivity;
import com.smartrobot.smartrobot.circle.FriendList;
import com.smartrobot.smartrobot.circle.NewFriend.Notify;
import com.smartrobot.smartrobot.circle.NewFriend.NewFriendUtil;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.pagerHolder.SocialCirlePagerHolder;
import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.util.User;
import com.websocket_lib.codebutler.android_websockets.WebSocketClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.net.URI;
import java.util.Arrays;
import java.util.List;

/**
 * Created by yeluojun on 2015/1/11.
 */
public class websocketHandle_2 {
    private String TAG = "========web_socket==========";

    List<BasicNameValuePair> extraHeaders=null;
   static  Context context ;



    WebSocketClient web_client =null;
    public websocketHandle_2(String url, String sessionID,Context context){
        try {

            //中断心跳
            heatBeat.setBreakHeart(true);

            this.context = context;

            setSession(sessionID);
            setWebSocket(url);

        }catch (Exception e){
            Log.e(TAG,"webSocket 创建失败");
        }
    }


    private void setSession(String sessionID){

        extraHeaders = Arrays.asList(
                new BasicNameValuePair("Cookie", sessionID)
        );
    }


    private void setWebSocket(String url){
        web_client = new WebSocketClient(URI.create(url), new WebSocketClient.Listener() {
            @Override
            public void onConnect() {
                try{

                    //线程睡眠500毫秒
                    Thread.sleep(500);

                    //设置心跳不中断
                    heatBeat.setBreakHeart(false);

                    //心跳开始
                    new heatBeat(context).ping();

                }catch (Exception e){
                    Log.e("心跳异常2", e.toString());
                    LogToSd.log_init();
                    LogToSd.error(e.toString());
                }
                Log.d(TAG, "Connected!");
                Log.e(TAG,"===================================链接成功================");


            }

            @Override
            public void onMessage(String message) {
                Log.d(TAG, String.format("Got string message! %s", message));
                Log.e(TAG,message);

                try{

                    JSONObject response = new JSONObject(message);
                    String msg_type = response.optString("type");


                    //心跳
                    if(msg_type!=null&&msg_type.equals("1")){
                        heatBeat.onPong();
                    }


                    //读取新的消息
                    if(msg_type!=null&&msg_type.equals("2")){

                    }

                    //用户未登录
                    if(msg_type.equals("7")){
                          Util.loginWithNoHandler(context);
                    }


                    //日程添加
                    if(msg_type.equals("5")){

                        String day = response.optString("day");
                        Log.e("===================>","  5 ");
                        HttpUtil.apiGetOneDayScheduleToFile(context,day);

                    }



                    //用户被人踢了
                    if(msg_type.equals("6")){
                        heatBeat.setBreakHeart(true);
                    }


                    //收到添加好友请求
                    if(msg_type.equals("8")){

                        if(User.getInstance()==null){
                            User.getUserInfo(context);
                        }

                        NewFriendUtil newFriendUtil = new NewFriendUtil(context,CommonFunc.stringToMD5(User.getInstance().getId()));

                        newFriendUtil.saveAndShowNewFriendTip("new",1);

                        int flag1 = newFriendUtil.saveData(response.optJSONObject("message"));


                        String  acName = CommonFunc.getRunningActivityName(context);
                        switch (flag1){
                            case 1:
                                if("com.smartrobot.smartrobot.activity.New_friend_activity".equals(acName)){
                                    newFriendUtil.addPojo(response.optJSONObject("message"),"insert");
                                }else{
                                    Notify.fRequestNotify(context);
                                }
                                break;
                            case 0:
                                if("com.smartrobot.smartrobot.activity.New_friend_activity".equals(acName)){
                                    newFriendUtil.addPojo(response.optJSONObject("message"),"update");
                                }else{
                                    Notify.fRequestNotify(context);
                                }
                                break;
                            default:
                                break;
                        }
                    }

                    //对方已经同意添加您为好友
                    if(msg_type.equals("9")){


                        if(User.getInstance()==null){
                            User.getUserInfo(context);
                        }
                        NewFriendUtil newFriendUtil = new NewFriendUtil(context, CommonFunc.stringToMD5(User.getInstance().getId()));
                        newFriendUtil.refreshFriendList(response.optJSONObject("message"));
                    }

                    //创建门店
                    if(msg_type.equals("10")){

                        //更改好友列表
                        FriendList friendList = new FriendList();
                        friendList.getFriendListBackGroup(SocialCirlePagerHolder.getFriendListHandler, context);


                        User.getInstance().setRole("店主");
                        User.saveUserInfo(context);

                        JSONObject obj = response.getJSONObject("message");
                        String name = obj.getString("s_name");

                        //通知您的理发师更新了日程
                        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                                .setSmallIcon(context.getApplicationInfo().icon)
                                .setWhen(System.currentTimeMillis()).setAutoCancel(true);

                        //设置状态栏提示
                        mBuilder.setTicker("您的店铺已经审核通过了，可以在个人中心查看管理地址！");
                        mBuilder.setContentTitle("店铺审核通过通知");
                        mBuilder.setContentText("您的店铺("+name+")已通过审核,可以在个人中心查看管理地址！");
                        //必须设置pendingintent，否则在2.3的机器上会有bug
                        Intent intent;

                        if(MainActivity.instance != null)
                            intent = new Intent(context, MainActivity.class);
                        else
                            intent = new Intent(context, SplashActivity.class);

                        PendingIntent pendingIntent = PendingIntent.getActivity(context, HttpUtil.CREATEORGAN_SUCCESS, intent, PendingIntent.FLAG_ONE_SHOT);
                        mBuilder.setContentIntent(pendingIntent);

                        //设置声音
                        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        mBuilder.setSound(alarmSound);

                        Notification notification = mBuilder.build();
                        notificationManager.cancel(HttpUtil.CREATEORGAN_SUCCESS);
                        notificationManager.notify(HttpUtil.CREATEORGAN_SUCCESS, notification);

                    }


                }catch (Exception e){
                    Log.e(TAG,"发生异常");
                    Log.e(TAG,e.toString());
                    LogToSd.error("发生异常");
                    LogToSd.error(e.toString());
                }


            }

            @Override
            public void onMessage(byte[] data) {

                Log.d(TAG, String.format("Got binary message! %s", ""));

            }

            @Override
            public void onPong(byte[] data) {
                heatBeat.onPong();
            }

            @Override
            public void onDisconnect(int code, String reason) {
                Log.d(TAG, String.format("Disconnected! Code: %d Reason: %s", code, reason));
                Log.e(TAG, String.format("Disconnected! Code: %d Reason: %s", code, reason));
                Log.e(TAG, "===============================on disconnect==================:"+reason);
                heatBeat.alive = false;
            }

            @Override
            public void onError(Exception error) {
                Log.e(TAG, "Error!", error);
                Log.e(TAG, "===============================on error==================:"+error);
                heatBeat.alive = false;
            }

        }, extraHeaders);


    }


    public WebSocketClient getWeb_client() {
        return web_client;
    }





    public static void init(Context _context){
        context = _context;
    }




}
